package lixp.security.config;

import lixp.security.service.UrlGrantedAuthority;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Collection;

/**
 * 用于权限注解
 * 我们需要自定义对hasPermission()方法的处理，
 * 就需要自定义PermissionEvaluator，创建类CustomPermissionEvaluator，实现PermissionEvaluator接口。
 */

@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {

    Logger logger = LoggerFactory.getLogger(CustomPermissionEvaluator.class);

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        // 获得loadUserByUsername()中注入的权限
        logger.info("CustomPermissionEvaluator---->hasPermission");
        logger.info("targetDomainObject---->" + targetDomainObject);
        logger.info("permission---->" + permission);
        Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) authentication.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            if (authority instanceof UrlGrantedAuthority) {
                UrlGrantedAuthority urlGrantedAuthority = (UrlGrantedAuthority) authority;
                String url = urlGrantedAuthority.getUri();
                String permissionVal = urlGrantedAuthority.getPermission();
                if (targetDomainObject.equals(url) && permission.equals(permissionVal)) {
                    return true;
                }
            }
        }


        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}
